<template>
  <div class="teacher-class-container">
    <el-card class="box-card">
      <div class="header">
        <h2>我的班级</h2>
        <div class="actions">
          <el-button type="primary" @click="goToAddClass" :icon="Plus">
            创建班级
          </el-button>
          <el-button type="info" @click="loadTeacherClasses" :loading="loading" :icon="Refresh">
            刷新
          </el-button>
          
          <div class="view-toggle">
            <el-tooltip content="卡片视图" placement="top">
              <el-button 
                :type="viewMode === 'card' ? 'primary' : ''" 
                @click="viewMode = 'card'"
                :icon="Grid"
              />
            </el-tooltip>
            <el-tooltip content="列表视图" placement="top">
              <el-button 
                :type="viewMode === 'list' ? 'primary' : ''" 
                @click="viewMode = 'list'"
                :icon="List"
              />
            </el-tooltip>
          </div>
        </div>
      </div>

      <div class="card-view" v-if="viewMode === 'card'" v-loading="loading">
        <el-row :gutter="20">
          <el-col 
            v-for="cls in teacherClasses" 
            :key="cls.id" 
            :xs="24" :sm="12" :md="8" :lg="6"
          >
            <el-card class="class-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="class-name">{{ cls.className }}</span>
                  <el-tag :type="cls.isActive ? 'success' : 'danger'" size="small">
                    {{ cls.isActive ? '活跃中' : '已结束' }}
                  </el-tag>
                </div>
              </template>
              
              <div class="class-info">
                <div class="info-item">
                  <span class="label">班级代码:</span>
                  <span>{{ cls.classCode }}</span>
                </div>
                <div class="info-item">
                  <span class="label">班主任:</span>
                  <span>{{ cls.teaName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">学生人数:</span>
                  <span>{{ cls.classStuNum }}</span>
                </div>
                <div class="info-item">
                  <span class="label">课程数量:</span>
                  <span>{{ cls.courseCount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间:</span>
                  <span>{{ formatDate(cls.createTime) }}</span>
                </div>
              </div>
              
              <div class="card-actions">
                <el-button-group>
                  <el-tooltip content="详情" placement="top">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click.stop="goToClassDetail(cls.id)"
                      :icon="View"
                    />
                  </el-tooltip>
                  <el-tooltip content="修改名称" placement="top">
                    <el-button 
                      type="warning" 
                      size="small" 
                      @click.stop="updateClassName(cls.id, cls.className)"
                      :icon="Edit"
                    />
                  </el-tooltip>
                  <el-tooltip content="课程管理" placement="top">
                    <el-button 
                      type="success" 
                      size="small" 
                      @click.stop="goToClassCourses(cls.id)"
                      :icon="Collection"
                    />
                  </el-tooltip>
                  <el-tooltip content="管理学生" placement="top">
                    <el-button 
                      type="info" 
                      size="small" 
                      @click.stop="openAddStudentDialog(cls.id)"
                      :icon="User"
                    />
                  </el-tooltip>
                  <el-tooltip content="删除班级" placement="top">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click.stop="deleteClass(cls.id)"
                      :icon="Delete"
                    />
                  </el-tooltip>
                </el-button-group>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="list-view" v-else v-loading="loading">
        <el-table :data="teacherClasses" style="width: 100%">
          <el-table-column prop="className" label="班级名称" width="180">
            <template #default="{ row }">
              <span class="class-name">{{ row.className }}</span>
              <el-tag 
                :type="row.isActive ? 'success' : 'danger'" 
                size="small"
                style="margin-left: 8px"
              >
                {{ row.isActive ? '活跃中' : '已结束' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="classCode" label="班级代码" width="120" />
          <el-table-column prop="teaName" label="班主任" width="120" />
          <el-table-column prop="classStuNum" label="学生人数" width="100" />
          <el-table-column prop="courseCount" label="课程数量" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button-group>
                <el-tooltip content="详情" placement="top">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click.stop="goToClassDetail(row.id)"
                    :icon="View"
                  />
                </el-tooltip>
                <el-tooltip content="修改名称" placement="top">
                  <el-button 
                    type="warning" 
                    size="small" 
                    @click.stop="updateClassName(row.id, row.className)"
                    :icon="Edit"
                  />
                </el-tooltip>
                <el-tooltip content="课程管理" placement="top">
                  <el-button 
                    type="success" 
                    size="small" 
                    @click.stop="goToClassCourses(row.id)"
                    :icon="Collection"
                  />
                </el-tooltip>
                <el-tooltip content="管理学生" placement="top">
                  <el-button 
                    type="info" 
                    size="small" 
                    @click.stop="openAddStudentDialog(row.id)"
                    :icon="User"
                  />
                </el-tooltip>
                <el-tooltip content="删除班级" placement="top">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click.stop="deleteClass(row.id)"
                    :icon="Delete"
                  />
                </el-tooltip>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-empty v-if="!loading && teacherClasses.length === 0" description="暂无班级数据"/>
    </el-card>

    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="showAddStudentDialog"
      title="管理班级学生"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="student-select-dialog">
        <el-transfer
          v-model="selectedStudents"
          :data="allStudents"
          :titles="['所有学生', '班级学生']"
          :props="{
            key: 'id',
            label: 'stuName'
          }"
          :loading="studentLoading"
          filterable
          filter-placeholder="输入学生姓名搜索"
        />
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: right">
          <el-button @click="showAddStudentDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="batchAddStudents"
            :loading="loading"
          >
            确认修改
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  ElMessage, 
  ElMessageBox, 
  ElDialog, 
  ElTransfer,
  ElTable,
  ElTableColumn,
  ElTag,
  ElTooltip,
  ElButtonGroup
} from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { teacherApi } from '@/api/teacher'
import { 
  Refresh, 
  Plus, 
  Edit, 
  User, 
  Delete,
  View,
  Collection,
  Grid,
  List
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { studentApi } from '@/api/students'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)
const teacherClasses = ref([])
const showAddStudentDialog = ref(false)
const allStudents = ref([])
const selectedStudents = ref([])
const studentLoading = ref(false)
const viewMode = ref('card')
const currentClassId = ref(null) // 添加这行修复错误

// 时间格式化
const formatDate = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm') : '未知时间'
}

// 获取教师ID
const getTeacherId = async () => {
  try {
    const userId = authStore.userId
    if (!userId) {
      ElMessage.warning('请先登录')
      return null
    }
    const response = await teacherApi.getTeacherByUid(userId)
    return response.id || response.data?.id
  } catch (error) {
    console.error('获取教师ID失败:', error)
    ElMessage.error('获取教师信息失败')
    return null
  }
}

// 加载教师班级数据
const loadTeacherClasses = async () => {
  loading.value = true
  try {
    const teacherId = await getTeacherId()
    if (!teacherId) return
    
    const response = await teacherApi.getTeacherClassRelations(teacherId)
    
    teacherClasses.value = response.map(item => ({
      id: item.classId,
      className: item.className,
      teaName: item.teaName,
      classCode: `CODE${item.classId}`,
      classStuNum: item.studentCount || 0,
      createTime: item.createTime,
      isActive: item.isActive !== false,
      courseCount: item.courseCount || 0
    }))
    
  } catch (error) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('加载班级列表失败')
  } finally {
    loading.value = false
  }
}

// 删除班级
const deleteClass = async (classId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个班级吗？删除后将无法恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    await teacherApi.deleteClass(classId)
    ElMessage.success('删除班级成功')
    loadTeacherClasses()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除班级失败:', error)
      ElMessage.error('删除班级失败')
    }
  } finally {
    loading.value = false
  }
}

// 修改班级名称
const updateClassName = async (classId, currentName) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入新的班级名称', '修改班级名称', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: currentName,
      inputPattern: /^.{2,50}$/,
      inputErrorMessage: '班级名称长度应在2-50个字符之间'
    })
    
    loading.value = true
    await teacherApi.updateClass({
      id: classId,
      className: value
    })
    ElMessage.success('班级名称修改成功')
    loadTeacherClasses()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改班级名称失败:', error)
      ElMessage.error('修改班级名称失败')
    }
  } finally {
    loading.value = false
  }
}

// 打开添加学生对话框
const openAddStudentDialog = async (classId) => {
  currentClassId.value = classId
  studentLoading.value = true
  try {
    const response = await studentApi.getAllStudents()
    const studentsData = Array.isArray(response.data) ? response.data : 
                       Array.isArray(response) ? response : []
    
    allStudents.value = studentsData.map(student => ({
      key: student.id,
      label: student.stuName || `学生${student.id}`,
      ...student
    }))
    
    const classStudents = await studentApi.getClassStudents(classId)
    const selectedStudentsData = Array.isArray(classStudents.data) ? classStudents.data : 
                               Array.isArray(classStudents) ? classStudents : []
    
    selectedStudents.value = selectedStudentsData.map(student => student.id)
    
    showAddStudentDialog.value = true
  } catch (error) {
    console.error('加载学生数据失败:', error)
    ElMessage.error('加载学生数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    studentLoading.value = false
  }
}

// 批量添加学生到班级
const batchAddStudents = async () => {
  try {
    loading.value = true
    await studentApi.batchAddStudentsToClass(currentClassId.value, selectedStudents.value)
    ElMessage.success('学生添加成功')
    showAddStudentDialog.value = false
    await loadTeacherClasses()
  } catch (error) {
    console.error('添加学生失败:', error)
    ElMessage.error('添加学生失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 跳转方法
const goToClassDetail = (classId) => {
  router.push(`/teacher-class/detail/${classId}`)
}

const goToClassCourses = (classId) => {
  router.push({
    name: 'CourseManagement',
    params: { classId: classId }
  })
}

const goToAddClass = () => {
  router.push('/teacher-class/add')
}

onMounted(async () => {
  const teacherId = await getTeacherId()
  if (teacherId) {
    loadTeacherClasses()
  }
})
</script>

<style scoped>
.el-button-group {
  display: flex;
  gap: 4px;
}

.class-card .card-actions {
  justify-content: center;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.teacher-class-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-toggle {
  display: flex;
  gap: 5px;
  margin-left: 10px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.view-toggle .el-button {
  border-radius: 0;
  border: none;
}

.card-view {
  min-height: 300px;
}

.list-view {
  min-height: 300px;
}

.class-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.class-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.class-name {
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-grow: 1;
}

.class-info {
  font-size: 14px;
  margin-bottom: 10px;
  flex-grow: 1;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-item .label {
  color: #606266;
  margin-right: 8px;
  width: 80px;
  font-weight: 500;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 10px;
}

.student-select-dialog {
  padding: 10px;
}

.student-select-dialog .el-transfer {
  display: flex;
  justify-content: center;
}

.el-table .cell {
  display: flex;
  align-items: center;
}

.el-table .class-name {
  font-weight: bold;
}

.el-table .el-button {
  margin: 0 3px;
}
</style>